package com.swak.fx.support.ui;

import org.controlsfx.glyphfont.FontAwesome;

import com.swak.fx.support.ui.UI.Colors;
import com.swak.utils.StringUtils;

import javafx.animation.FadeTransition;
import javafx.scene.Cursor;

/**
 * 附着在其他的组件内部
 * 
 * @author 618lf
 */
public class UIAttach extends UIIcon {

	FadeTransition fader = null;
	boolean visible = false;

	public UIAttach(FontAwesome.Glyph icon) {
		super(icon);
		this.fader = new FadeTransition(UI.Durations.FADE_DURATION, this);
	}

	public UIAttach Attach(UITextField field) {
		this.color(Colors.FontXX);
		this.setCursor(Cursor.DEFAULT);
		this.setOnMouseReleased(e -> field.clear());
		this.managedProperty().bind(field.editableProperty());
		this.visibleProperty().bind(field.editableProperty());
		field.textProperty().addListener((c) -> {
			String text = field.getText();
			boolean isTextEmpty = StringUtils.isBlank(text);
			if (isTextEmpty == visible) {
				visible = !isTextEmpty;
				fadeTo(visible);
			}
		});
		field.rightProperty().set(this);
		return this;
	}

	private void fadeTo(boolean visible) {
		fader.stop();
		fader.setFromValue(visible ? 0.0 : 1.0);
		fader.setToValue(visible ? 1.0 : 0.0);
		fader.play();
	}

	public static UIAttach Clear() {
		return new UIAttach(UI.Icons.CLOSE);
	}
}